package com.supervision.manage.controller;

import com.fly.base.annotation.AuthPermission;
import com.fly.base.common.DataResponse;
import com.fly.base.misc.upload.FileSystemClient;
import com.fly.base.misc.upload.UploadObject;
import com.supervision.domain.exception.WrongParamException;
import io.swagger.annotations.Api;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * Created by whis on 11/18/18
 * @author whis
 */
@RestController
@RequestMapping("/static")
@Api(tags = "文件上传")
public class StaticController {
    private static Logger logger = org.slf4j.LoggerFactory.getLogger(StaticController.class);

    @RequestMapping(value = "/file/upload", method = RequestMethod.POST)
    @AuthPermission(needToken = false)
    public DataResponse imgUpload(@RequestParam("file") MultipartFile file) throws IOException {
        DataResponse response = DataResponse.create();
        if (file.isEmpty()) {
            throw new WrongParamException("上传文件不能为空");
        }

        String fileOriginalFilename = file.getOriginalFilename(); // 文件原始名字
        String mimeType = file.getContentType();                    // 文件mime

        String ext = FilenameUtils.getExtension(fileOriginalFilename);          // 文件扩展名
        String fileHash = DigestUtils.md5Hex(file.getInputStream());
        String ossKey = FileSystemClient.getFileKey(fileHash + "." + ext);

        UploadObject uploadResult = FileSystemClient.getClient().upload(fileOriginalFilename, file.getInputStream(), ossKey, mimeType);

        response.put("origin_name", fileOriginalFilename);
        response.put("filename", uploadResult.getFileKey());
        response.put("file_url", uploadResult.getUrl());
        return response;
    }
}
